package applet.connection;

import java.io.IOException;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Random;

public class MediaReceiver {
	
	public int SIZE = 100;

	private String _localAddress = null;
	private int _localPort = 0;
	private int _localRTCPPort = 0;
	private String _remoteAddress = null;
	private int _remotePort = 0;
	private int _remoteRTCPPort = 0;

	private DatagramSocket _socket = null;
	private DatagramSocket _socketRTCP = null;
	private DatagramPacket _buffer = null;

	
	public MediaReceiver(String raddress, int rport,String laddress, int lport) throws UnknownHostException {
		// TODO Auto-generated constructor stub
		_remoteAddress = raddress;
		_remotePort = rport;
		_remoteRTCPPort = rport + 1;
		_localAddress = laddress;
		_localPort = lport;
		_localRTCPPort = lport + 1;
		boolean done = false;
		Random r = new Random();
		
		int inc = 0;
		
		while (!done){
			try{
				InetAddress ia = InetAddress.getLocalHost();
				_socket = new DatagramSocket(_localPort,ia);
				_socketRTCP = new DatagramSocket(_localRTCPPort,ia);
				done = true;
			}catch (SocketException se){
				inc =r.nextInt(3);
				_localPort =+ inc;
				_localRTCPPort =+ inc;
			}
		}
	}
	
	public DatagramSocket get_socket(){
		return _socket;
	}
	
	public DatagramPacket read() throws IOException{
		SIZE = _socket.getReceiveBufferSize();
		_buffer = new DatagramPacket(new byte[SIZE], SIZE);
		_socket.receive(_buffer);
		return _buffer;
	}
	
	public DatagramPacket readRTCP() throws IOException{
		SIZE = _socketRTCP.getReceiveBufferSize();
		_buffer = new DatagramPacket(new byte[SIZE], SIZE);
		_socketRTCP.receive(_buffer);
		return _buffer;
	}
	
	public void write(Serializable s) throws IOException{
		byte[] data = s.toString().getBytes();
		DatagramPacket _d = new DatagramPacket(data,data.length);
		_d.setSocketAddress(new InetSocketAddress(_remoteAddress,_remotePort));
		_socket.send(_d);
	}
	
	public void writeRTCP(Serializable s) throws IOException{
		byte[] data = s.toString().getBytes();
		DatagramPacket _d = new DatagramPacket(data,data.length);
		_d.setSocketAddress(new InetSocketAddress(_remoteAddress,_remoteRTCPPort));
		_socket.send(_d);
	}
	
	public void write(DatagramPacket s) throws IOException{
		s.setSocketAddress(new InetSocketAddress(_remoteAddress,_remotePort));
		_socket.send(s);
	}
	
	public void writeRTCP(DatagramPacket s) throws IOException{
		s.setSocketAddress(new InetSocketAddress(_remoteAddress,_remoteRTCPPort));
		_socket.send(s);
	}

	public void close() {
		_socket.close();
		
	}
	
}
